package com.wardrobe.soa.backend.operator;


import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.wardrobe.soa.backend.admin.SessionConstant;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Sha512Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class AdminOperatorService {
    private static Logger logger = LoggerFactory.getLogger(AdminOperatorService.class);
    @Resource
    private AdminOperatorDao adminOperatorDao;


    public int getCurUserId() {
        return getCurrentUser().getId();
    }

    public AdminOperatorBean getCurrentUser() {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        System.out.println(session.getTimeout());
        if (session != null) {
            AdminOperatorBean currentUser = getFromSession(session);
            if (currentUser == null) {
                currentUser = loadFromDbBySubject(subject);
                session.setAttribute(SessionConstant.LOGINUSER, currentUser);
            }
            return currentUser;
        } else {
            return null;
        }
    }

    private AdminOperatorBean loadFromDbBySubject(Subject subject) {
        final Integer currentUserId = (Integer) subject.getPrincipal();
        if (currentUserId != null) {
            return adminOperatorDao.queryAdminById(currentUserId);
        } else {
            return null;
        }
    }

    private AdminOperatorBean getFromSession(Session session) {
        AdminOperatorBean op = (AdminOperatorBean) session.getAttribute(SessionConstant.LOGINUSER);
        return op;
    }

    //
    public AdminOperatorBean findByUsername(String uname) {
        final AdminOperatorBean admin = this.adminOperatorDao.findByUserName(uname);
        if (admin == null) {
            logger.warn("not found user:{}", uname);
            return new AdminOperatorBean();
        } else {
            return admin;
        }
    }

    public int addAdminOperator(AdminOperatorBean bean) {
        final AdminOperatorBean checkUser = this.findByUsername(bean.getNickName());
        if (checkUser != null && checkUser.getId() != 0) {
            //用户已经存在
            return -2;
        }
        if (!bean.getPwd().equals(bean.getConfirmPwd())) {
            //输入两次密码不同
            return -3;
        }
        String encodedPassword = new Sha512Hash(bean.getPwd()).toBase64();
        bean.setPwd(encodedPassword);

        return adminOperatorDao.addAdmin(bean);
    }

    public Map<Integer, String> getIdNameMapping() {

        Map<Integer, String> ret = new HashMap<Integer, String>();
        try {
            List<Map<String, Object>> operators = adminOperatorDao.queryAdminList();
            for (Map<String, Object> o : operators) {
                ret.put((Integer) (o.get("user_id")), (String) o.get("nickname"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    public Map<String, Object> getOperatorList() {
        final HashMap<String, Object> retMap = Maps.newHashMap();

        final List<Map<String, Object>> operatorList = adminOperatorDao.queryAdminList();
        final Iterator<Map<String, Object>> iterator = operatorList.iterator();
        while (iterator.hasNext()) {
            final Map<String, Object> operatorMap = iterator.next();
            final Date createTime = (Date) operatorMap.get("create_time");
            operatorMap.put("create_time_str", "");
        }
        retMap.put("list", operatorList);

        return retMap;
    }

    public int delOperator(int operatorId) {
        return adminOperatorDao.delOperator(operatorId);
    }

    public int updateOperator(AdminOperatorBean bean) {
        return adminOperatorDao.updateOperator(bean);
    }

    public AdminOperatorBean queryById(AdminOperatorBean bean) {
        return adminOperatorDao.queryAdminById(bean.getId());
    }

    public int resetPwd(AdminOperatorBean bean) {
        String encodedPassword = new Sha512Hash("000000").toBase64();
        bean.setPwd(encodedPassword);
        return adminOperatorDao.resetPwd(bean);
    }

    public List<RoleBean> queryRoles() {
        return adminOperatorDao.queryAllRoles();
    }

    public List<PermissionBean> queryPermission() {
        return adminOperatorDao.queryAllPermissions();

    }

    public int addRole(RoleBean bean) {
        return adminOperatorDao.addRole(bean);
    }

    public int addPermission(PermissionBean bean) {
        return adminOperatorDao.addPermission(bean);
    }

    public int delRole(RoleBean bean) {
        return adminOperatorDao.delRole(bean);
    }

    public int delPermission(PermissionBean bean) {
        return adminOperatorDao.delPermission(bean);
    }

    public int updateRole(RoleBean bean) {
        return adminOperatorDao.updateRole(bean);
    }

    public int updatePermissino(PermissionBean bean) {
        return adminOperatorDao.updatePermission(bean);
    }

    public List<Map<String, Object>> queryPermissionsByRoleId(int roleId) {
        return adminOperatorDao.queryPermissionsByRoleId(roleId);
    }


    public Set<String> getPermissionsByOperatorId(AdminOperatorBean operator) {
        Set<String> permissionCodes = Sets.newHashSet();

        final List<Map<String, Object>> permissionsList = adminOperatorDao.queryPermissionByOperatorId(operator.getId());
        for (Map<String, Object> permiss : permissionsList) {
            permissionCodes.add(String.valueOf(permiss.get("tag_code")));
        }
        return permissionCodes;

    }

    public List<Map<String, Object>> getRoleByOperatorId(AdminOperatorBean operator) {
        return adminOperatorDao.queryRoleByOperatorId(operator.getId());

    }

    public Set<String> getRoleStrByOperatorId(AdminOperatorBean operator) {
        Set<String> roleCodes = Sets.newHashSet();

        final List<Map<String, Object>> permissionsList = adminOperatorDao.queryRoleByOperatorId(operator.getId());
        for (Map<String, Object> permiss : permissionsList) {
            roleCodes.add(String.valueOf(permiss.get("role_name")));
        }
        return roleCodes;

    }

    public int removePermissionFromRole(RoleBean bean) {
        return adminOperatorDao.removePermissionFromRole(bean);
    }

    public int addPermissionFromRole(RoleBean bean) {
        return adminOperatorDao.addPermissionFromRole(bean);
    }

    public int removeRoleFromOperator(AdminOperatorBean bean) {
        return adminOperatorDao.removeRoleFromOperator(bean);
    }

    public int addRoleFromOperator(AdminOperatorBean bean) {
        return adminOperatorDao.addRoleFromOperator(bean);
    }

}
